package com.example.springcache.service.impl;

import com.example.springcache.pojo.People;
import com.example.springcache.service.DemoService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "com.bjsxt")  //加了这个注解以后  cacheable里面就不需要再写了 默认就是这个
public class DemoServiceImpl implements DemoService {
    @Override
    //固定字符串都要加单引号
    @Cacheable(key = "'demo'")
    public String demo() {
        System.out.println("damo仿法1");
        return "demo";
    }

    @Override
    @Cacheable(key = "'selectById'+#id")  //因为每次查询到的值不一样 所以key也不一样
    public String selectById(long id) {
        System.out.println("执行了selectbyid:"+id);
        return "selectbyid"+id;
    }

    @Override
    @CachePut(key = "'selectById'+#id")
    public String selectByIdUpdate(long id) {
        System.out.println("修改操作selectByIdUpdate:"+id);
        return "selectByIdUpdate"+id;
    }

    /**
     * 缓存对象
     * @param id
     * @param name
     * @return
     */
    @Override
    @Cacheable(key = "'selectByUsername'+#id+':'+#name")
    public People selectByUsername(long id, String name) {
        People people = new People();
        people.setId(1l);
        people.setName("zhangsan");

        return people;
    }

    @Override
    @Cacheable(key = "'selectById2'+#id",condition = "#id!=5")  //unless = "#result==null",
    public People selectById2(long id) {
        System.out.println("selectById2 方法执行完以后执行 如果 unless为null 不缓存 condition 条件成立才缓存 先判断再进方法");
        return null;
    }

    @CacheEvict(key = "'demo'")
    public void delete(){
        System.out.println("删除缓存");
    }

}
